package com.onlyxiahui.common.utils.base.lang.util.collection;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Description <br>
 * Date 2021-05-02 17:52:45<br>
 * 
 * @author XiaHui [onlovexiahui@qq.com]<br>
 * @since 1.0.0
 */

public class ListMapUtil {
	
	public interface GetKey<V, K> {

		K getKey(V v);
	}

	public interface GetValue<B, K> {

		B getByKey(K k);
	}

	public interface ValueBack<T> {

		void back(T value);
	}

	public static <T, K, B> void backListByKeys(
			List<T> list,
			ListConvertUtil.Convert<K, T> c,
			GetValue<List<B>, List<K>> getValue,
			ValueBack<List<B>> back) {
		List<K> ids = ListConvertUtil.convert(list, c);
		List<B> vs = getValue.getByKey(ids);
		back.back(vs);
	}

	public static <T, K, B> void backMapByKeys(
			List<T> list,
			ListConvertUtil.Convert<K, T> c,
			GetValue<List<B>, List<K>> getValue,
			GetKey<B, K> getKey,
			ValueBack<Map<K, B>> back) {
		ListMapUtil.backListByKeys(list, c, getValue, (items) -> {
			Map<K, B> map = new HashMap<>();
			if (null != items) {
				for (B b : items) {
					K key = getKey.getKey(b);
					map.put(key, b);
				}
			}
			back.back(map);
		});
	}

	public static <T, K> void backListToMap(
			List<T> list,
			GetKey<T, K> getKey,
			ValueBack<Map<K, T>> back) {
		Map<K, T> map = new HashMap<>();
		if (null != list) {
			for (T b : list) {
				K key = getKey.getKey(b);
				map.put(key, b);
			}
		}
		back.back(map);
	}

	public static <T, K> void backListToMapList(
			List<T> list,
			GetKey<T, K> getKey,
			ValueBack<Map<K, List<T>>> back) {
		Map<K, List<T>> map = new HashMap<>();
		if (null != list) {
			for (T b : list) {
				K key = getKey.getKey(b);
				List<T> items = map.get(key);
				if (null == items) {
					items = new ArrayList<>();
					map.put(key, items);
				}
				items.add(b);
			}
		}
		back.back(map);
	}
}
